package com.hl.payServer.controller;

import com.hl.payServer.model.ResultModel;
import com.hl.payServer.service.PayTradeInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.TreeMap;

@RestController
@RequestMapping("/notifies")
public class NotifiesController {

    private static final Logger log = LoggerFactory.getLogger(NotifiesController.class);
    @Autowired
    private PayTradeInfoService payTradeInfoService;

    /**
     * 支付宝支付回调
     * @param request 请求对象
     * @return 处理结果
     */
    @RequestMapping(value = "/aliPay", method = RequestMethod.POST)
    public String aliPay(HttpServletRequest request, HttpServletResponse response){
        TreeMap<String,String> params = null;
        try {
            params = getParams(request);
            log.error("支付宝支付回调："+params);
            PrintWriter out = response.getWriter();
            out.print(payTradeInfoService.aliPayNotifies(params));
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 微信支付回调
     *
     * @param request 请求对象
     * @return 处理结果
     */
    @RequestMapping(value = "/wePay", method = RequestMethod.POST)
    public ResponseEntity<ResultModel> paid(HttpServletRequest request) {
        String notifyXml = getPostRequestBody(request);
        if (notifyXml.isEmpty()) {
            return new ResponseEntity("body is null", HttpStatus.OK);
        }
        String s = null;
        try{
            s = payTradeInfoService.wePayNotifies(notifyXml);
        }catch (Exception e){
            s = e.getMessage();
            log.error("微信支付回调异常", e);
        }
        return new ResponseEntity(s==null?"fail":s, HttpStatus.OK);
    }


    /**
     * 动态遍历获取所有收到的参数
     * @param request
     * @return
     */
    public TreeMap<String, String> getParams(HttpServletRequest request) throws UnsupportedEncodingException {
        //通知传输的编码为GBK
        request.setCharacterEncoding("utf-8");
        Map reqMap = request.getParameterMap();
        TreeMap<String, String> map = new TreeMap<String, String>();
        for(Object key: reqMap.keySet()){
            String value = ((String[])reqMap.get(key))[0];
            map.put(key.toString(), value);
        }
        return map;
    }

    /**
     * 获取http请求传来的字节码参数
     * @param req
     * @return
     */
    public static String getPostRequestBody(HttpServletRequest req) {
        if ("POST".equals(req.getMethod())) {
            StringBuilder sb = new StringBuilder();
            try (BufferedReader br = req.getReader()) {
                char[] charBuffer = new char[128];
                int bytesRead;
                while ((bytesRead = br.read(charBuffer)) != -1) {
                    sb.append(charBuffer, 0, bytesRead);
                }
            } catch (IOException e) {
                log.warn("failed to read request body, cause: {}", e);
            }
            return sb.toString();
        }
        return "";
    }


}
